﻿app.controller('PayBillCtrl', ['$scope', '$http','httpPlus','testData','$stateParams','$state','$q',function ($scope, $http,httpPlus,testData,$stateParams,$state,$q) {
    var weixinJSBridge = function (_method, _data) {
        var deferred = $q.defer();
        if (WeixinJSBridge == undefined) {
            deferred.reject("WeixinJSBridge is undefined");
        } else if (WeixinJSBridge.invoke == undefined) {
            deferred.reject("WeixinJSBridge.invoke is undefined");
        } else {
            WeixinJSBridge.invoke(_method, _data, function (res) {
                // alert(JSON.stringify(res));
                if (res.err_msg == "get_brand_wcpay_request:ok") {
                    deferred.resolve();
                } else {
                    deferred.reject({
                        ResultMsg: '支付已取消'
                    });
                }
            });
        }
        return deferred.promise;
    };
    var currCoupon = [];
    var billGUID = $stateParams.billid;
    console.log('billGUID',billGUID);
    //账单详情对象
    $scope.billData = {
        showCouponList:false,
        currCoupon:undefined,
        billDetail:{},
        billItems:[],
        card:{
            list:[],
            currCard:undefined,
            changeCard_change:function(){
                console.log($scope.billData.card.currCard);
                getDiscountData($scope.billData.card.currCard,$scope.billData.currCoupon);
            }
        },
        couponsOfFilter:[],
        payType:{
          list:  [{
                name: '微信支付',
                type: 'wechatpay',
                rest: undefined,
                points: undefined
            }],
           currPayType:undefined,
            changePayType_change:function(){
                console.log($scope.billData.payType.currPayType);
                getDiscountData($scope.billData.card.currCard,$scope.billData.currCoupon);
            }
        },
        invoice:{
            enabled:false,
            isPersonal:'true',
            title:'',
            enabled_change:function(){
                if($scope.billData.invoice.enabled){
                    $scope.billData.invoice.isPersonal = 'true'
                    scrollView();
                }
            },
            isPersonal_change:function(){
                if($scope.billData.invoice.isPersonal == 'false'){
                    scrollView();
                }
            }
        },
        isPayResult:'0',
        payResult:undefined,
        wechatCouponSwitch:0,
        platformCouponSwitch:0,
        showChooseCoupon:false,
        //进入选择优惠券
        chooseCoupon_click:function(){
            $scope.billData.showCouponList = true;
        },
        //选中优惠券
        chooseCurrCoupon_click:function(data){
            $scope.billData.currCoupon = data;
            console.log($scope.billData.currCoupon )
            getDiscountData($scope.billData.card.currCard,$scope.billData.currCoupon);
            $scope.billData.showCouponList = false;
        },
        //退去选择优惠券
        returnPayBill_click:function(){
            $scope.billData.currCoupon = undefined;
            getDiscountData($scope.billData.card.currCard,$scope.billData.currCoupon);
            $scope.billData.showCouponList = false;
        },
        //支付订单事件
        btnPay_click:function(){
            //if($scope.billData.billDetail.tableno == '' || $scope.billData.billDetail.tableno == undefined){
            //    return alert('请输入台号!');
            //}
            if($scope.billData.billDetail.CustomerMealTime == ''){
                return alert('预定时间不能为空');
            }else if($scope.billData.billDetail.CustomerMealTime.getTime() != new Date($scope.dataCustomerMealTime).getTime() ){
                if($scope.billData.billDetail.CustomerMealTime.getTime() < new Date().setMinutes(new Date().getMinutes()+15))
                return alert('预定时间必须为15分钟后的时间');
            };
            if($scope.billData.payType.currPayType == 'cardpay'){
                httpPlus
                    .MMB2RRRApi('MBBillHis/QuickPayByMemberCard', {
                    _billGUID: $scope.billData.billDetail.BillGUID,
                    _cardCode: $scope.billData.card.currCard.CardCode,
                    _tableNo: '',
                    _invoiceTitle: '',
                    _arrCouponSelected: currCoupon,
                    _remark:$scope.billData.billDetail.CustomerRemark

                })
                    .then(function(data){
                        $state.go('wx.reservePayResult',{'billid':billGUID})
                    })
                    .catch(function(err){
                        alert(err.ResultMsg);
                        $state.go('wx.reserveOrders')
                    })
            }else {
                httpPlus
                    .MMB2RRRApi('MBBillHis/QuickPayByWeChatPrepay', {
                        _billGUID: billGUID,
                        _cardCode: $scope.billData.card.currCard.CardCode,
                        _tableNo: '',
                        _invoiceTitle: '',
                        _arrCouponSelected: currCoupon,
                        _remark:$scope.billData.billDetail.CustomerRemark
                    })
                    .then(function(_data){
                        if (_data.GetBrandWCPayRequestData.appId == "")
                            return $scope.billData.isPayResult = '1';
                        else
                            return weixinJSBridge('getBrandWCPayRequest', _data.GetBrandWCPayRequestData);
                    })
                    .then(function(){
                        if($scope.billData.isPayResult == '0'){
                            return httpPlus.MMB2RRRApi('MBBillHis/QuickPayByWeChatQuery', {
                                _billGUID: billGUID
                            });
                        }
                    })
                    .then(function(){
                        $state.go('wx.reservePayResult',{'billid':billGUID})
                    })
                    .catch(function(err){
                        if(err.ResultCode == 100 && err.ResultMsg == '订单已支付'){
                            $state.go('wx.reservePayResult',{'billid':billGUID})
                        }else {
                            alert(err.ResultMsg);
                            $state.go('wx.reserveOrders')
                        }
                    })
            }
        },
        //返回修改订单
        returnEdit_click:function(){
            $state.go('wx.reserveOrder',{'billid':billGUID,'code':$stateParams.code})
        }
    };
    $scope.$watch('billData.billDetail.CustomerMealTime',function(val){
        if(val){
            getDiscountData();
        }
    });
/*    $scope.$watch('billData.billDetail.CustomerRemark',function(val){
        if(val){
            getDiscountData();
        }
    });*/
    //预支付
    var getDiscountData = function (currCard, currCoupon) {
            console.log(currCard);
            if(currCoupon == undefined){
                 currCoupon = [];
            }else {
                 currCoupon = [{
                    CouponCode:currCoupon.Code,
                    SelectionSequence: 1,
                    CouponType:'PlatformCoupon'
                }]
            }
            httpPlus.MMB2RRRApi('MBBillHis/QuickPay2Preview', {
                _billGUID:  billGUID,
                _cardCode: currCard.CardCode,
                _arrCouponSelected:currCoupon,
                _billHis:{
                    CustomerCount:1,
                    CustomerMealTime: $scope.billData.billDetail.CustomerMealTime,
                    CustomerRemark:$scope.billData.billDetail.CustomerRemark,
                    BillType: 'YuDian'
                }
            })
                .then(function (data) {
                    $scope.billData.payResult = data.BillPrepay;
                    $scope.billData.wechatCouponSwitch = data.wechatCouponSwitch;
                    $scope.billData.platformCouponSwitch = data.platformCouponSwitch;
                    if( data.wechatCouponSwitch != 0 || data.platformCouponSwitch != 0){
                        $scope.billData.showChooseCoupon = true;
                    };
                    if(data.Coupons.length > 0 ){
                        $scope.billData.couponsOfFilter = [
                                {
                                    type: 'available',
                                    title: '可用优惠券',
                                    list: data.Coupons.filter(function (_item) {
                                        return _item.FilterStat == 'available';
                                    })
                                },
                                {
                                    type: 'un-available',
                                    title: '不可用优惠券',
                                    list: data.Coupons.filter(function (_item) {
                                        return _item.FilterStat != 'selected' && _item.FilterStat != 'available';
                                    })
                                }]
                    }

                })
                .catch(function(err){
                    alert(JSON.stringify(err.ResultMsg));
                })

    }
    //初始化数据
    httpPlus
        .MMB2RRRApi('MBBillHis/InitQuickPayPayBill2Page',{
            _billGUID:billGUID
        })
        .then(function (data) {
            console.log('zhende',data);
            $scope.dataCustomerMealTime = data.BillHead.CustomerMealTime;
            $scope.billData.billDetail = data.BillHead;
            $scope.billData.billDetail.CustomerMealTime = new Date(data.BillHead.CustomerMealTime.replace(/-/g, "/"));
            $scope.billData.card.list = data.MemberCardList;
            $scope.billData.billItems = data.BillItems;
            $scope.billData.card.currCard = $scope.billData.card.list[0];
            $scope.billData.payType.currPayType = $scope.billData.payType.list[0].type;

            if($scope.billData.card.currCard !=undefined && $scope.billData.payType.list.length == 1){
                $scope.billData.payType.list.push({
                    name:'会员卡',
                    type:'cardpay',
                    rest:$scope.billData.card.currCard.Balance,
                    points:$scope.billData.card.currCard.AvailablePoint
                });
                getDiscountData($scope.billData.card.currCard,$scope.billData.currCoupon);
            }
        })
        .catch(function(err){
            alert(JSON.stringify(err.ResultMsg));
        })
}]);